package main

import "github.com/hashicorp/consul/api"

// 注册服务
func Register(name string, id string, tags []string, address string, port int) {
	config := api.DefaultConfig()
	config.Address = "127.0.0.1:8500"
	client, err := api.NewClient(config)
	if err != nil {
		panic(err)
	}
	//健康检查
	//check := &api.AgentServiceCheck{
	//	HTTP:     "http://192.168.3.17:8300/health",
	//	Interval: "10s",
	//	Timeout:  "1s",
	//}
	registration := api.AgentServiceRegistration{
		Name:    name,
		ID:      id,
		Tags:    tags,
		Address: address,
		Port:    port,
		//Check:   check,
	}
	err = client.Agent().ServiceRegister(&registration)
	if err != nil {
		panic(err)
	}
}

// 获取所有服务
func AllService() {
	config := api.DefaultConfig()
	config.Address = "127.0.0.1:8500"
	client, err := api.NewClient(config)
	if err != nil {
		panic(err)
	}

	services, err := client.Agent().Services()
	if err != nil {
		panic(err)
	}
	for _, service := range services {
		println(service.ID)
	}
}

// 过滤服务
func ServicesWithFilter() {
	config := api.DefaultConfig()
	config.Address = "127.0.0.1:8500"
	client, err := api.NewClient(config)
	if err != nil {
		panic(err)
	}

	//`ID=="king1"`
	services, err := client.Agent().ServicesWithFilter(`ID=="king1"`)
	for k, v := range services {
		println(k, v)
	}
}

func main() {
	//tags := []string{"king3"}
	//Register("king3", "king3", tags, "127.0.0.1:8500", 50053)
	//AllService()
	ServicesWithFilter()
}
